import ProductModel from "../../../models/Product";
import UserModel from "../../../models/User";
import Crypt from "../../../utils/Crypt";
import config from "../../../config/config";

const productModel = new ProductModel()
const userModel = new UserModel()

Page({
  data: {
    page: 0,
    pageSize: 10,
    list: [],
    busy: false,
    baseUrl: config.app_base_url
  },
  onLoad: function (options) {
    this._getList()
  },

  onReachBottom() {
    this._getList(true)
  },

  _getList(append = false) {
    if (this.data.busy === false) {
      this.setData({
        busy: true,
        page: this.data.page + 1
      })
      productModel.favList({ ...this.data }).then(response => {
        let { data } = response
        data = Crypt.parse(data)
        if (data.list.length === 0) {
          this.setData({ busy: true })
        } else {
          this.setData({ busy: false })
          if (append) {
            this.setData({ list: this.data.list.concat(data.list) })
          } else {
            this.setData({ list: data.list })
          }
        }
      })
    }
  },

  handleClick(event) {
    const id = event.currentTarget.dataset.item.product.id
    wx.navigateTo({
      url: '/sub_product/pages/detail/index?id=' + id
    })
  },

  onCancel(event) {
    const item = event.currentTarget.dataset.item
    const id = item.product.id
    userModel.checkLogin().then(() => {
      productModel.removeFav({ id }).then(() => {
        wx.showToast({
          title: '取消成功'
        })
        const list = this.data.list.filter(x => x.id !== item.id)
        this.setData({ list })
      })
    })
  }
});
